<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 警告部分 -->
      <el-alert
        title="注意：只允许选择三级分类！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 联级选择部分 -->
      <el-row class="cate_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 联级选择器 options获取数据源 v-model选中的id值双向绑定-->
          <el-cascader
            :options="cateList"
            :props="cateProps"
            :cateProps="{ expandTrigger: 'hover' }"
            v-model="selectedCateKeys"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs标签页部分 绑定当前选择页-->
      <el-tabs v-model="activeName" @tab-click="handleCateClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >动态参数</el-button
          >
          <!-- 动态参数列表展示部分 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开层 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
              <!-- 循环渲染tag标签，attr_vals展示 -->
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加tag -->
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
                >+ New Tag</el-button
              >
              </template>
              
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="warning"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeEditDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >静态属性</el-button
          >
          <!-- 静态参数列表展示部分 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开层 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
              <!-- 循环渲染tag标签，attr_vals展示 -->
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加tag -->
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
                >+ New Tag</el-button
              >
              </template>
              
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog"
                  >编辑</el-button
                >
                <el-button
                  type="warning"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeEditDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框属性 -->
    <el-dialog
      :title="`添加` + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容:添加参数的对话框 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框属性 -->
    <el-dialog
      :title="`修改` + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <!-- 内容:添加参数的对话框 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'params',
  data() {
    return {
      cateList: [],
      //级联选择框的配置对象
      cateProps: {
        value: 'cat_id', //选择的值
        label: 'cat_name', //展示的值
        children: 'children', //父子节点的嵌套属性
      },
      //选中的id值 级联选择框
      selectedCateKeys: [],
      //tabs当前选择的标签页
      activeName: 'many',
      //从数据库获取的动态参数数据
      manyTableData: [],
      //从数据库获取的静态参数数据
      onlyTableData: [],
      addDialogVisible: false,
      //添加表单数据
      addForm: {
        attr_name: '',
      },
      //添加表单数据规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      //控制编辑对话框的显示与隐藏
      editDialogVisible: false,
      //编辑表单数据
      editForm: {},
      //编辑表单验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.cateList = res.data
      this.$message.success('获取商品分类成功')
      //   console.log(this.cateList)
    },
    //级联选择器变化触发该函数
    handleChange() {
      this.getParamsData()
    },
    //tabs点击事件的处理函数,变换tabs栏
    handleCateClick() {
      // console.log(this.activeName)
      this.getParamsData()
    },
    //获取参数列表
    async getParamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData=[]
        // console.log('选择的不是三级分类')
      }
      // console.log(this.selectedCateKeys)
      //当处于三级时展示参数列表
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      // this.$message.success('获取参数列表成功')
      // console.log(res.data)
      //每一项都循环  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      res.data.forEach((item) => {
        //三元表达式，如果不为空不分割
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
         //控制添加tag标签的显示与隐藏
        //添加tag标签输入内容
        item.inputVisible=false
        item.inputValue=''
      })

      //将数据attr_vals分割成数组,并赋值回去
      // 将获取的数据进行分别挂载
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    //监测关闭重制表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //验证表单并添加数据到数据库
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('数据请求成功')
        }
        this.addDialogVisible = false
        this.getParamsData()
        this.$message.success('数据请求成功')
      })
    },
    //显示编辑对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('查询展示数据失败')
      }
      this.$message.success('查询数据成功')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    //点击确定修改表单信息
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('数据提交失败')
        }
        //   console.log(res.data);
        this.getParamsData()
        this.editDialogVisible = false
        this.$message.success('数据提交成功')
      })
    },
    //   删除对话框：根据id删除对应的参数项
    async removeEditDialog(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //用户取消删除操作
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }

      //删除参数的业务逻辑
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('数据提交失败')
      }
      //   console.log(res.data);
      this.getParamsData()
      this.$message.success('数据提交成功')
    },
    //按下enter执行函数
   async handleInputConfirm(row) {
      // console.log('ok');
      //填的数据非空需要提交数据，为空清理数据
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
      row.inputVisible=false
        return
      }
      //若没有return,则证明输入的内容，需要后续处理
      //添加数据并且清除前后按钮
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
       //需要发起请求将数据保存到数据库中
     this.saveAttrVals(row)
    },
    //将添加的tag标签保存到数据库
   async saveAttrVals(row) {
      //需要发起请求将数据保存到数据库中
     const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
       })
       if (res.meta.status !== 200) {
        return this.$message.error('上传数据失败')
      }
      this.$message.success('上传数据成功')
    },
    //点击展示输入框
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    //关闭（or删除）tag标签
    handleClose(i, row) {
      //删除数据中的一项
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },


  computed: {
    // 什么情况下禁用按钮
    // eslint-disable-next-line vue/return-in-computed-property
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    //获取当前选择的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    //同用一个对话框，动态控制属性添加的位置
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>

<style lang="less" scoped>
.cate_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}

.input-new-tag{
  width: 120px;
}
</style>
